package com.example.servicetest

import android.Manifest
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.IBinder
import android.telecom.TelecomManager
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import com.android.internal.telephony.ITelephony
import java.lang.reflect.Method


class ListenCallService:Service() {
    private  val TAG = "ListenCallService"
    private lateinit var telephoneManager: TelephonyManager
    private val listener=object : PhoneStateListener() {
        override fun onCallStateChanged(state: Int, phoneNumber: String?) {
            when(state){
                TelephonyManager.CALL_STATE_IDLE -> {
                    //空闲
                    Log.e(TAG, "空闲")
                }
                TelephonyManager.CALL_STATE_OFFHOOK -> {
                    //摘机
                    Log.e(TAG, "摘机")

                }
                TelephonyManager.CALL_STATE_RINGING -> {
                    //正在响铃
                    Log.e(TAG, "响铃")
                    Log.e(TAG, "$phoneNumber:111" )
                    if (phoneNumber == "11000") {

                        endCall()
                    }
                }
            }
        }
    }

//    private fun endCall() {
////        TODO("Not yet implemented")
//        //通过反射调用隐藏的API
//        //得到隐藏类的Class对象
//        //通过反射调用隐藏的API
//        //得到隐藏类的Class对象
//        val c = Class.forName("android.os.ServiceManager")
//        //得到方法所对应的Method对象
//        //得到方法所对应的Method对象
//        val method = c.getMethod("getService", String::class.java) as Method
//        method.isAccessible=true
//        //调用方法
//        //调用方法
//        //得到接口对象
//        //得到接口对象
//        val telephony = ITelephony.Stub.asInterface(method.invoke(null, TELEPHONY_SERVICE) as IBinder)
//        //结束通话
//        //结束通话
//        telephony.endCall()
//    }

    @RequiresApi(Build.VERSION_CODES.P)
    private fun endCall() {
//        if(Build.VERSION.SDK_INT>=28){
            val manager = getSystemService(Context.TELECOM_SERVICE) as TelecomManager

        try {
            manager.endCall()
        } catch (e: Exception) {
        }

    }

    override fun onBind(intent: Intent?): IBinder? {
//        TODO("Not yet implemented")
        return null
    }

    override fun onCreate() {
        super.onCreate()
        Log.e(TAG, "onCreate: ")
        this.telephoneManager=this.getSystemService(Context.TELEPHONY_SERVICE)
        as TelephonyManager
        this.telephoneManager.listen(this.listener, PhoneStateListener.LISTEN_CALL_STATE)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG, "onDestroy: ")

        this.telephoneManager.listen(this.listener, PhoneStateListener.LISTEN_NONE)
    }
}
